import 'dart:io';
import 'package:casdon/modules/demo/application/notification/demo_ocr_notifier.dart';
import 'package:casdon/modules/demo/domain/states/demo_orc_state.dart';
import 'package:casdon/modules/demo/ui/screen/demo_ocr_failed.dart';
import 'package:casdon/modules/demo/ui/widgets/ai_animation.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 食材识别
class DemoOcrScreen extends ConsumerStatefulWidget {
  final String imagePath;
  const DemoOcrScreen({super.key, required this.imagePath});

  @override
  ConsumerState<DemoOcrScreen> createState() => _DemoOcrScreenState();
}

class _DemoOcrScreenState extends ConsumerState<DemoOcrScreen> {
  late final ProviderSubscription<DemoOcrState> _subscription;
  @override
  void initState() {
    super.initState();

    // 监听 OCR 状态变化
    _subscription = ref.listenManual<DemoOcrState>(
      demoOcrProvider(widget.imagePath),
      (pri, next) => _handleListenState(pri, next),
    );
  }

  @override
  void dispose() {
    _subscription.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(demoOcrProvider(widget.imagePath));

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          /// 底层拍摄或选择的图片
          Positioned.fill(
            child: Image.file(File(state.imagePath), fit: BoxFit.contain),
          ),

          /// 加载层动画
          if (state.isLoading)
            Positioned.fill(
              child: Container(
                color: Colors.black.withOpacity(0.4),
                child: const Center(
                  child: SizedBox(
                    width: 150,
                    height: 150,
                    child: AIAnimation(),
                  ),
                ),
              ),
            ),

          /// 返回按钮
          Positioned(
            left: 8,
            top: 32,
            child: IconButton(
              icon: const Icon(Icons.arrow_back),
              color: Colors.white,
              onPressed: () => Navigator.of(context).pop(),
            ),
          ),
        ],
      ),
    );
  }

  void _handleListenState(DemoOcrState? previous, DemoOcrState next) {
    if (!mounted) return;
    if (previous?.isLoading == true && next.isLoading == false) {
      if (next.ocrResult != null) {
        DemoOcrSuccessRoute(next.imagePath).push(context);
      } else {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (_) => DemoOcrFailed(imagePath: next.imagePath),
            fullscreenDialog: true,
          ),
        );
      }
    }
  }
}
